package l1j.opqlo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.utils.SQLUtil;

public class NewYear {

	class timer extends TimerTask {
		private ScheduledFuture<?> _timer;

		@Override
		public void run() {
			try {
				NewYear.this.load();
			} catch (final Exception e) {
				_log.log(Level.WARNING, "紅包卡更新處理時間軸異常重啟", e);
				PcOtherThreadPool.get().cancel(this._timer, false);
				new timer().start();
			}

		}

		public void start() {
			final int timeMillis = 600000;
			this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(
					this, timeMillis, timeMillis);
		}
	}

	private static NewYear _instance;
	private static final Logger _log = Logger
			.getLogger(NewYear.class.getName());

	public static NewYear getInstance() {
		if (_instance == null) {
			_instance = new NewYear();
		}
		return _instance;
	}

	public boolean isLoad;

	private final String sql = "select char_id,count from character_items where item_id = 255550 order by count DESC limit ";
	private Connection con;
	private static String[] _valueList;
	private final ArrayList<NewYear_temp> _ChaList;

	//

	public NewYear() {
		this._ChaList = new ArrayList<NewYear_temp>();
		_valueList = new String[21];
		for (int i = 0; i < 10; i++) {
			this._ChaList.add(i, new NewYear_temp());
		}

		try {
			this.load();
			new timer().start();
		} catch (final SQLException e) {
			e.printStackTrace();
		}
	}

	public String[] getAllValue() {
		if (this.isLoad) {
			return null;
		}
		return _valueList;
	}

	private void load() throws SQLException {
		ResultSet pstm = null;
		this.con = DatabaseFactory.get().getConnection();
		NewYear_temp temp;
		for (int i = 0; i < 10; i++) {
			pstm = this.con.prepareStatement(this.sql + i + ",1;")
					.executeQuery();
			if (pstm.next()) {
				temp = this._ChaList.get(i);
				if (temp != null) {
					temp.setChaId(pstm.getInt("char_id"));
					temp.setCount(pstm.getInt("count"));
				}
			}
		}
		SQLUtil.close(pstm);
		SQLUtil.close(this.con);
		this.isLoad = true;
		int ii = 1;
		for (final NewYear_temp temp2 : this._ChaList) {
			_valueList[ii] = temp2.getName();
			_valueList[ii + 10] = String.valueOf(temp2.getCount());
			ii++;
		}
		this.isLoad = false;
	}
}
